﻿using System;
using System.Collections.Generic;

using System.Text;
using Common.Logging;
using Efficient.Domain;

namespace Efficient.DataAccess
{
    public class KeywordQuery
    {
        private string queryString;
        private readonly IList<Keyword> keywordSet = new List<Keyword>();
        private static readonly ILog logger = LogManager.GetLogger(typeof(KeywordQuery));

        public string QueryString
        {
            get { return queryString; }
            set { queryString = value; }
        }

        public IList<Keyword> KeywordSet
        {
            get { return keywordSet; }
        }

        public void SetKeywordToQuery(IQuery query, string keyword)
        {
            if (query == null)
            {
                throw new NullReferenceException("query is null");
            }
            if (string.IsNullOrEmpty(keyword))
            {
                return;
            }
            bool debug = logger.IsDebugEnabled;
            if (this.keywordSet.Count > 0)
            {
                foreach (Keyword key in this.keywordSet)
                {
                    switch (key.MatchMode)
                    {
                        case KeyMode.StartWith:
                            query.SetString(key.KeywordParam, string.Concat(keyword, "%"));
                            break;
                        case KeyMode.EndWith:
                            query.SetString(key.KeywordParam, string.Concat("%", keyword));
                            break;
                        case KeyMode.Contain:
                        default:
                            query.SetString(key.KeywordParam, string.Concat("%", keyword, "%"));
                            break;
                    }

                    if (debug)
                    {
                        logger.Debug(string.Format("关键字参数:{0} 匹配模式:{1}", key.KeywordParam, key.MatchMode));
                    }
                }
            }
        }
    }
}
